package com.boby.lib_common.util

import android.content.Context
import android.content.SharedPreferences
import com.boby.lib_common.BaseApplication
import com.boby.lib_common.extens.otherwise
import com.boby.lib_common.extens.yes


class SharedPrefUtil {
    companion object {
         fun<T> findPreference(key: String,defValue: T,prefsName:String ="CDX"): T {
           val prefs = getPrefs(prefsName)
           return  when (defValue) {
                 is Int ->  prefs.getInt(key, defValue)
                 is Long -> prefs.getLong(key, defValue)
                 is Float -> prefs.getFloat(key, defValue)
                 is Boolean -> prefs.getBoolean(key, defValue)
                 is String -> prefs.getString(key, defValue)
                 else -> {
                     throw IllegalArgumentException("Unsupported type.")
                 }
             }as T
        }


         fun<T>  putPreference(key: String, value: T,prefsName:String="CDX",commit:Boolean= false) {
             val prefs = getPrefs(prefsName)
            val edit = prefs.edit().apply {
                when (value) {
                    is Int -> putInt(key, value)
                    is Long -> putLong(key, value)
                    is Float -> putFloat(key, value)
                    is Boolean -> putBoolean(key, value)
                    is String -> putString(key, value)
                    else -> throw IllegalArgumentException("Unsupported type.")
                }
            }
            commit.yes { edit.commit() }.otherwise { edit.apply() }
        }
        private fun getPrefs(prefName: String): SharedPreferences = BaseApplication.instance().getSharedPreferences(prefName, Context.MODE_PRIVATE)
    }
}